package com.yanzhenjie.andserver.sample.controller.base;

import com.yanzhenjie.andserver.sample.ServerHttpCode;
import com.yanzhenjie.andserver.sample.SessionExpireManager;
import com.yanzhenjie.andserver.sample.component.E7Exception;

import cn.hutool.core.util.StrUtil;


/**
 * 作者: Tao
 * 日期: 2023/2/22
 * 时间: 10:12
 * 描述: controller基类
 */
public abstract class BaseController {

    /**
     * 检查session
     *
     * @param cookie
     * @param path
     */
    protected void checkSession(String cookie, String path) {
        if (StrUtil.isBlankIfStr(cookie)) {
            throwUnAuthException("Access Denied. User not logged in.", path);
        }
        log("checkSession-->cookie = " + cookie);
        String[] split = cookie.split("=");
        if (split == null || split.length < 2) {
            throwUnAuthException("Access Denied. User not logged in.", path);
        }
        String sessionId = split[1];
        log("checkSession-->sessionId = " + sessionId);
        if (!SessionExpireManager.containsKey(sessionId)) {
            throwUnAuthException("Access Denied. User not logged in.", path);
        }
        /*如果session未过期，刷新树间*/
        if (SessionExpireManager.isExpired(sessionId)) {
            SessionExpireManager.refreshExpired(sessionId);
        } else {
            log("checkSession-->设备session已过期");
            throwUnAuthException("Access Denied. User not logged in.", path);
        }
    }

    protected void throwException(String detail, String path) {
        throw new E7Exception(ServerHttpCode.FAIL_BAD_REQUEST,
                path,
                detail,
                -1);
    }

    protected void throwServerErrorException(String detail, String path) {
        throw new E7Exception(ServerHttpCode.FAIL_INTERNAL_SERVER_ERROR,
                path,
                detail,
                -1);
    }

    protected void throwUnAuthException(String detail, String path) {
        throw new E7Exception(ServerHttpCode.FAIL_UNAUTHORIZED,
                path,
                detail,
                -1);
    }

    protected abstract void log(String msg);

}
